from flask import Blueprint, request, jsonify
from .models import *

user_bp = Blueprint('user', __name__, url_prefix='/user')

@user_bp.route('/register', methods=['POST'])
def register():
    try:
        # 获取请求体中的 JSON 数据
        data = request.get_json()

        # 提取用户信息
        user_id = data.get('id')
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        gender = data.get('gender')
        weight = data.get('weight')
        height = data.get('height')
        shoe_size = data.get('shoeSize')

        # 打印用户信息
        # print(f"Received user information:")
        # print(f"ID: {user_id}")
        # print(f"Username: {username}")
        # print(f"Email: {email}")
        # print(f"Password: {password}")
        # print(f"Gender: {gender}")
        # print(f"Weight: {weight}")
        # print(f"Height: {height}")
        # print(f"Shoe Size: {shoe_size}")


        # 创建用户对象
        user = User(
            id=user_id,
            username=username,
            email=email,
            password=password,
            gender=gender,
            weight=weight,
            height=height,
            shoe_size=shoe_size)

        # 添加到数据库
        db.session.add(user)
        db.session.commit()

        # 返回成功响应
        response = {
            'message': 'User register successfully'
        }
        return jsonify(response), 200

    except Exception as e:
        # 处理异常情况
        error_message = str(e)
        # print(error_message)
        response = {
            'error': error_message
        }
        return jsonify(response), 400



@user_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')



    if not username or not password:
        return jsonify({'message': 'Username and password are required'}), 400

    user = User.query.filter_by(username=username).first()

    if user and user.password == password:

        return jsonify({'message': 'Login successful'}), 200
    else:
        return jsonify({'message': 'Invalid username or password'}), 401



@user_bp.route('/logout', methods=['GET'])
def logout():
    try:
        # 清除会话数据
        return jsonify({'message': 'Logout successful'}), 200
    except Exception as e:
        error_message = str(e)
        print(error_message)
        return jsonify({'error': error_message}), 400